package ute.mvc.controller.portal.lecturer;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ute.mvc.dto.QuestionDTO;
import ute.mvc.model.Question;
import ute.mvc.model.QuestionPool;
import ute.mvc.model.Subject;
import ute.mvc.model.User;
import ute.mvc.service.QuestionPoolService;
import ute.mvc.service.SubjectService;
import ute.mvc.service.UserService;
import ute.mvc.util.IdUtil;
import ute.mvc.util.JsonObject;

@Controller
@RequestMapping(value = { "/lecturer/{lecturerId}/{openCourseId}/{subjectId}/pool" })
public class QuestionPoolController {

	@Autowired
	SubjectService subjectService;
	@Autowired
	QuestionPoolService poolService;
	@Autowired
	UserService userService;

	@RequestMapping(value = { "/info/{poolId}" }, method = RequestMethod.GET)
	public String getPoolInfo(@PathVariable String poolId, Model model) {

		QuestionPool pool = poolService.getQuestionPool(poolId);
		model.addAttribute("pool", pool);
		return "pool_info";
	}

	@RequestMapping(value = { "/add" }, method = RequestMethod.GET)
	public String getAddPool(@PathVariable String subjectId, Model model) {

		QuestionPool pool = new QuestionPool();
		model.addAttribute("pool", pool);
		return "pool_add";
	}

	@RequestMapping(value = { "/add" }, method = RequestMethod.POST)
	public String addPool(@PathVariable int lecturerId,
			@PathVariable String subjectId,
			@Valid @ModelAttribute("pool") QuestionPool pool,
			BindingResult result, Model model) {

		if (result.hasErrors()) {
			return "pool_add";
		}

		if (!poolService.isValidName(pool.getQuestionPoolName())) {
			result.rejectValue("questionPoolName", "nameexist");
			return "pool_add";
		}
		Subject subject = subjectService.getSubjectById(subjectId);
		pool.setSubject(subject);

		User lecturer = userService.getUserById(lecturerId);
		pool.setLecturer(lecturer);

		// Find largest pool id
		String maxId = poolService.getMaxIdInSubject(subject);
		String newId = IdUtil.getNewQuestionPoolIdInSubject(maxId);

		// Set pool ID
		pool.setQuestionPoolId(subjectId + "_" + newId);
		poolService.addQuestionPool(pool);
		return "redirect:info/" + pool.getQuestionPoolId();
	}

	/**
	 * Get Pool Information
	 * 
	 * @param poolId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "/edit/{poolId}" }, method = RequestMethod.GET)
	public String getEditPool(@PathVariable String poolId, Model model) {

		QuestionPool pool = poolService.getQuestionPool(poolId);
		model.addAttribute("pool", pool);
		return "pool_edit";
	}

	/**
	 * Update Pool
	 * 
	 * @param poolId
	 * @param model
	 * @return pool
	 */
	@RequestMapping(value = { "/edit/{poolId}" }, method = RequestMethod.POST)
	public String updatePool(@Valid @ModelAttribute("pool") QuestionPool pool,
			BindingResult result, Model model) {

		if (result.hasErrors())
			return "pool_edit";

		// Get data
		QuestionPool oldPool = poolService.getQuestionPool(pool
				.getQuestionPoolId());

		if (!poolService.isValidName(pool.getQuestionPoolName())) {
			if (!oldPool.getQuestionPoolId().equals(
					poolService.getPoolByName(pool.getQuestionPoolName())
							.getQuestionPoolId())) {
				result.rejectValue("questionPoolName", "nameexist");
				return "pool_edit";
			}
		}

		pool.setSubject(oldPool.getSubject());
		pool.setLecturer(oldPool.getLecturer());

		poolService.updateQuestionPool(pool);
		return "redirect:../info/" + pool.getQuestionPoolId() + "";
	}

	@RequestMapping(value = { "/delete/{poolId}" }, method = RequestMethod.GET)
	public String deletePool(@PathVariable String poolId, Model model) {
		System.out.println("Delete pool " + poolId);
		QuestionPool pool = poolService.getQuestionPool(poolId);
		poolService.deleteQuestionPool(pool);
		return "redirect:../";
	}

	/**
	 * Pool Detail
	 * 
	 * @param poolId
	 * @param model
	 * @return all question in pool
	 */
	@RequestMapping(value = { "/detail/{poolId}" }, method = RequestMethod.GET)
	public String getPool(@PathVariable String poolId, Model model) {

		QuestionPool pool = poolService.getQuestionPool(poolId);
		
		if(pool == null){
			return "redirect:../";
		}
		List<Question> listQuestion = (List<Question>) pool.getListQuestion();
		List<QuestionDTO> listQuestionDTO = new ArrayList<QuestionDTO>();
		model.addAttribute("pool", pool);
		// Convert to DTO before send to client
		for (Question q : listQuestion) {
			listQuestionDTO.add(new QuestionDTO(q));
		}
		model.addAttribute("listQuestion", listQuestionDTO);
		return "pool_detail";
	}

	/**
	 * List Question Pool OK
	 * 
	 * @param subjectId
	 * @param model
	 * @return
	 */

	@RequestMapping(value = { "/" }, method = RequestMethod.GET)
	public String getAllPool(@PathVariable String subjectId, Model model) {

		Subject subject = subjectService.getSubjectById(subjectId);
		model.addAttribute("subject", subject);
		return "pool_list";
	}

	@RequestMapping(value = { "/lookup" }, method = RequestMethod.GET)
	public String getAllPoolLookup(Model model) {

		return "pool_lookup";
	}
	
	@RequestMapping(value = { "/question/{poolId}" }, method = RequestMethod.GET)
	@ResponseBody
	public int getNumberQuestionInPool(@PathVariable String poolId){
		QuestionPool pool = poolService.getQuestionPool(poolId);
		System.out.println("PoolNumber");
		return pool.getListQuestion().size();
	}

	/**
	 * OK
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = { "/listJSON" }, method = RequestMethod.GET)
	@ResponseBody
	public JsonObject getAllPool(@PathVariable int lecturerId,
			@PathVariable String subjectId) {

		User lecturer = userService.getUserById(lecturerId);
		Subject subject = subjectService.getSubjectById(subjectId);

		List<QuestionPool> list = poolService.getPoolBySubjectLecturer(subject,
				lecturer);
		JsonObject jsonObject = new JsonObject();
		jsonObject.setAaData(list);
		jsonObject.setiTotalDisplayRecords(list.size());
		jsonObject.setiTotalRecords(list.size());
		jsonObject.setsEcho(1);
		return jsonObject;
	}
}
